package com.tvunetworks.center.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.tvunetworks.center.common.constant.LocalConstant;
import com.tvunetworks.center.common.constant.UserBehaviorConstant;
import com.tvunetworks.center.common.exception.ClientException;
import com.tvunetworks.center.common.model.*;
import com.tvunetworks.center.common.model.param.PeerIdsParam;
import com.tvunetworks.center.common.util.JsonUtil;
import com.tvunetworks.center.common.util.MyUtil;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.gs.model.Device;
import com.tvunetworks.center.user.annotation.Logined;
import com.tvunetworks.center.user.constant.UserConstant;
import com.tvunetworks.center.user.constant.UserDeviceRecordConstant;
import com.tvunetworks.center.user.model.BindAndUnbindUserReceiverCenterParam;
import com.tvunetworks.center.user.model.OwnerByListPeerIdParam;
import com.tvunetworks.center.user.model.PageInfoBookMarkParam;
import com.tvunetworks.center.user.model.param.*;
import com.tvunetworks.center.user.model.result.ResultConstant;
import com.tvunetworks.center.user.model.vo.*;
import com.tvunetworks.center.user.service.BookmarkDeviceService;
import com.tvunetworks.center.user.service.RoleUserService;
import com.tvunetworks.center.user.service.UserBehaviorService;
import com.tvunetworks.center.user.service.UserDeviceService;
import com.tvunetworks.center.user.service.feign.DeviceFeignService;
import com.tvunetworks.center.user.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: tvucc-user
 * @description: UserDeviceController
 * @author lebronchen
 * @create: 2019-03-14 11:49
 **/
@RestController
@RequestMapping("/userDevice")
@Slf4j
public class UserDeviceController {


    @Value("${defaultLivePeerName}")
    private String defaultLivePeerName;
    @Value("${pushLiveUrl}")
    private String pushLiveUrl;

    @Autowired
    private UserDeviceService userDeviceService;
    @Autowired
    private DeviceFeignService deviceFeignService;


    @Autowired
    private UserBehaviorService userBehaviorService;

    @Autowired
    private BookmarkDeviceService bookmarkDeviceService;
    @Autowired
    private RoleUserService roleUserService;

    /**
     * 绑定或解绑用户和设备R之间的关系
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @PostMapping("/bindAndUnbindUserReceiverCenter")
    public Result bindAndUnbindUserReceiverCenter(@Logined LoginUser loginUser, @RequestBody BindAndUnbindUserReceiverCenterParam param) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        List<String> userIds = new ArrayList<>();
        userIds.add(param.getUserId());
        if (StringUtils.isNotEmpty(param.getUnBindPeerId())) {
            List<String> unbindPeerId = new ArrayList<>(Arrays.asList(param.getUnBindPeerId().split(",")));
            userDeviceService.unbindUserReceiverCenter(loginUser.getId(), unbindPeerId, userIds);
        }
        if (StringUtils.isNotEmpty(param.getBindPeerId())) {
            List<String> bindPeerId = new ArrayList<>(Arrays.asList(param.getBindPeerId().split(",")));
            userDeviceService.bindUserReceiverCenter(loginUser.getId(), bindPeerId, userIds);
        }
        if (StringUtils.isNotEmpty(param.getBindPeerId()) || StringUtils.isNotEmpty(param.getUnBindPeerId())) {
            roleUserService.deleteByUserId(param.getUserId());
        }
        return ResultUtil.success();
    }

    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @PostMapping("/reloadUser")
    public Result<Object> reloadUser(@Logined LoginUser loginUser, @RequestBody ReloadUserParam param) {
        userDeviceService.reloadUser(loginUser, param);
        return ResultUtil.success();
    }

    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @PostMapping("/reloadReceiver")
    public Result<Object> reloadReceiver(@Logined LoginUser loginUser, @RequestBody ReloadReceiverParam param) {
        userDeviceService.reloadReceiver(loginUser, param.getRids());
        return ResultUtil.success();
    }

    /**
     *
     * @param param param
     * @return Result
     */
    @PostMapping("/pageUserUnbindRPairedSource")
    public Result pageUserUnbindRPairedSource(@RequestBody PageUserUnbindRPairedSourceParam param) {
        PageInfo<Device> pageInfo = userDeviceService.pageUserUnbindRPairedSource(param);
        return ResultUtil.success(pageInfo);
    }

    /**
     * 查询用户 R 绑定的 Source
     *
     * @param param param
     * @return Result
     */
    @PostMapping("/pageUserRPairedSource")
    public Result pageUserRPairedSource(@RequestBody PageUserRPairedSourceParam param) {
        PageInfo<SearchUserDeviceVo> pageInfo = userDeviceService.pageUserRPairedSource(param);
        return ResultUtil.success(pageInfo);
    }


    /**
     * 查询 R 绑定的 Source
     *
     * @param param param
     * @return Result
     */
    @PostMapping("/pageRPairedSource")
    public Result pageRPairedSource(@RequestBody PageUserUnbindRPairedSourceParam param) {
        PageInfo<Device> pageInfo = userDeviceService.pageRPairedSource(param);
        return ResultUtil.success(pageInfo);
    }

    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @PostMapping("/pageBookingChannel")
    public Result pageBookingChannel(@Logined LoginUser loginUser, @RequestBody PageBookingChannelParam param) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        param.setUserId(loginUser.getId());
        PageInfo<Device> pageInfo = userDeviceService.pageBookingChannel(param);
        return ResultUtil.success(pageInfo);
    }

    /**
     *
     * @param loginUser loginUser
     * @param peerId peerId
     * @return Result
     */
    @GetMapping("/isUserOwner")
    public Result isUserOwner(@Logined LoginUser loginUser, @RequestParam String peerId) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        boolean result = true;
        String userRole = loginUser.getRole();
        if (LocalConstant.UserRole.ADMIN.equals(userRole) || LocalConstant.UserRole.USER.equals(userRole)) {
            result = userDeviceService.isUserOwner(loginUser.getId(), peerId);
        }
        return ResultUtil.success(result);
    }

    /**
     *  根据peerId ,获取是否有creatEvent/owner权限
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @PostMapping("/isUserOwnerByListPeerId")
    public Result isUserOwnerByListPeerId(@Logined LoginUser loginUser, @RequestBody OwnerByListPeerIdParam param) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        return  userDeviceService.isUserOwnerByListPeerId(loginUser, param);
    }


    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     * @throws Exception 编译异常
     */
    @PostMapping("/listR")
    public Result<Object> listR(@Logined LoginUser loginUser,
                                @RequestBody SearchDeviceParam param) throws Exception {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        Long time = System.currentTimeMillis();
        log.error("ListR start ==loginUser:" + loginUser.getEmail() + "==Time=" + time);

        try {
            UserBehavior userBehavior = new UserBehavior();
            userBehavior.setUserId(loginUser.getId())
                    .setPn(UserBehaviorConstant.Pn.ADVANCE_CONTROL)
                    .setServerName(UserBehaviorConstant.ServerName.USER)
                    .setRemark(UserBehaviorConstant.Remark.LIST_R)
                    .setContent(JsonUtil.toJsonStr(param));
            userBehaviorService.setUserBehavior(userBehavior);
        } catch (IOException e) {
            log.error("ListR Set user behavior ==loginUser:" + loginUser.getEmail() + "==Time=" + time);
            log.error("Set user behavior [{}] exception", "listR", e);
        }
        ListRResult listRResult = null;
        try {
            listRResult = userDeviceService.listReceiverControlRAndLastUsed(loginUser.getId(), param);
            log.error("ListR listRResult ==loginUser:" + loginUser.getEmail() + "==Time=" + time);

            List<Device> result = new ArrayList<>();

            for (Device device : result) {
                if (StringUtils.isEmpty(device.getLivePeerName()) && StringUtils.equals(device.getStatus(), LocalConstant.DeviceStatus.LIVING)) {
                    device.setLivePeerName(defaultLivePeerName);
                }
            }
        } catch (Exception e) {
            log.error("listReceiverControlRAndLastUsed Exception :[{}]", e);
            log.error("ListR listReceiverControlRAndLastUsed ==loginUser:" + loginUser.getEmail() + "==Time=" + time);
            listRResult = new ListRResult();
        }
        log.error("ListR End ==loginUser:" + loginUser.getEmail() + "==Time=" + time);
        return ResultUtil.success(listRResult);
    }

    /**
     *
     * @param loginUser loginUser
     * @param param  param
     * @return Result
     */
    @PostMapping("/homePageR")
    public Result<Object> homePageR(@Logined LoginUser loginUser,
                                    @RequestBody SearchDeviceParam param) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }

        try {
            UserBehavior userBehavior = new UserBehavior();
            userBehavior.setUserId(loginUser.getId())
                    .setPn(UserBehaviorConstant.Pn.HOME)
                    .setServerName(UserBehaviorConstant.ServerName.USER)
                    .setRemark(UserBehaviorConstant.Remark.PAGE_R)
                    .setContent(JsonUtil.toJsonStr(param));
            userBehaviorService.setUserBehavior(userBehavior);
        } catch (IOException e) {
            log.error("Home Page Set user behavior [{}] exception", "pageR", e);
        }
        PageInfo<Device> devicePageInfo = userDeviceService.pageR(loginUser.getId(), param);
        return ResultUtil.success(devicePageInfo);
    }

    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @PostMapping("/advanceControlPageR")
    public Result<Object> advanceControlPageR(@Logined LoginUser loginUser,
                                              @RequestBody SearchDeviceParam param) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }

        try {
            UserBehavior userBehavior = new UserBehavior();
            userBehavior.setUserId(loginUser.getId())
                    .setPn(UserBehaviorConstant.Pn.ADVANCE_CONTROL)
                    .setServerName(UserBehaviorConstant.ServerName.USER)
                    .setRemark(UserBehaviorConstant.Remark.PAGE_R)
                    .setContent(JsonUtil.toJsonStr(param));
            userBehaviorService.setUserBehavior(userBehavior);
        } catch (IOException e) {
            log.error("Advance Control Page Set user behavior [{}] exception", "pageR", e);
        }
        PageInfo<Device> devicePageInfo = userDeviceService.pageR(loginUser.getId(), param);
        return ResultUtil.success(devicePageInfo);
    }

    /**
     * 查询 R 的 source
     *
     * @param loginUser loginUser
     * @param param     param 中的receiverId 不能为null
     * @return Result Result
     */
    @PostMapping("/listRPairSource")
    public Result<Object> listRPairSource(@Logined LoginUser loginUser,
                                          @RequestBody SearchDeviceParam param) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }

        if (StringUtils.isBlank(param.getRid())) {
            return ResultUtil.paramError();
        }

        List<Device> list = userDeviceService.listReceiverControlSource(loginUser.getId(), param);
        return ResultUtil.success(list);
    }


    /**
     * Query the source list under the current login accountlistRPairSource
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @PostMapping("/listUserSource")
    public Result<Object> listUserSource(@Logined LoginUser loginUser,
                                         @RequestBody SearchDeviceParam param) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        List<Device> list = userDeviceService.listMySource(loginUser.getId(), param);
        return ResultUtil.success(list);
    }

    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @PostMapping("/pageRPairSource")
    public Result<Object> pageRPairSource(@Logined LoginUser loginUser,
                                          @RequestBody SearchDeviceParam param) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }

        if (StringUtils.isBlank(param.getRid())) {
            return ResultUtil.paramError();
        }
        try {
            Result<String> result = null;
            UserBehavior userBehavior = new UserBehavior();
            userBehavior.setUserId(loginUser.getId())
                    .setPn(UserBehaviorConstant.Pn.ADVANCE_CONTROL)
                    .setServerName(UserBehaviorConstant.ServerName.USER)
                    .setRemark(UserBehaviorConstant.Remark.R_PAIR_SOURCE)
                    .setContent(JsonUtil.toJsonStr(param));
            userBehaviorService.setUserBehavior(userBehavior);
        } catch (IOException e) {
            log.error("Set user behavior exception", e);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Result<String> result = null;
                //根据Rid 查询R的sourceTypeList
                try {
                    result = userDeviceService.getRSourceTypeList(param.getRid());
                    if (result != null) {
                        userBehaviorService.setRSourceListToRedis(param.getRid(), result.getResult());
                    }
                } catch (Exception e) {
                    log.error("getRSourceTypeList Exception:[{}]", e);
                }
            }
        }).start();
        PageInfo<Device> list = userDeviceService.pageReceiverControlSource(loginUser.getId(), param);
        return ResultUtil.success(list);
    }

    /**
     *
     * @param loginUser loginUser
     * @return Result
     */
    @GetMapping("/advancedControlWithInit")
    public Result advancedControlWithInit(@Logined LoginUser loginUser) {

        if (loginUser == null) {
            return ResultUtil.noLogin();
        }

        // 获取behavior,如果没有就进行初始化
        UserBehavior userBehavior = new UserBehavior()
                .setUserId(loginUser.getId())
                .setPn(UserBehaviorConstant.Pn.ADVANCE_CONTROL)
                .setServerName(UserBehaviorConstant.ServerName.USER)
                .setRemark(UserBehaviorConstant.Remark.LIST_R + "," + UserBehaviorConstant.Remark.R_PAIR_SOURCE);

        Result<Map<String, String>> userBehaviors = userBehaviorService.getUserBehaviors(userBehavior);

        SearchDeviceParam listRParam;
        SearchDeviceParam rPairSourceParam;


        if (StringUtils.equals(ResultUtil.SUCCESS, userBehaviors.getErrorCode())) {
            Map<String, String> result = userBehaviors.getResult();

            String listRParamStr = result.get(UserBehaviorConstant.Remark.LIST_R);

            if (StringUtils.isEmpty(listRParamStr)) {
                listRParam = SearchDeviceParam.initForListR();
            } else {
                try {
                    listRParam = JsonUtil.toObject(listRParamStr, SearchDeviceParam.class);
                } catch (IOException e) {
                    listRParam = SearchDeviceParam.initForListR();
                    log.error("parse LIST_R user behavior failed", e);
                }
            }

            String rPairSourceParamStr = result.get(UserBehaviorConstant.Remark.R_PAIR_SOURCE);

            if (StringUtils.isEmpty(rPairSourceParamStr)) {
                rPairSourceParam = SearchDeviceParam.initForRPairSource();
            } else {
                try {
                    rPairSourceParam = JsonUtil.toObject(rPairSourceParamStr, SearchDeviceParam.class);
                } catch (IOException e) {
                    rPairSourceParam = SearchDeviceParam.initForRPairSource();
                    log.error("parse R_PAIR_SOURCE user behavior failed", e);
                }
            }
        } else {
            listRParam = SearchDeviceParam.initForListR();
            rPairSourceParam = SearchDeviceParam.initForRPairSource();
        }

        // get behavior finish

        ListRResult listRResult = null;


        listRParam.setToken(false);
        try {
            listRResult = userDeviceService.listReceiverControlRAndLastUsed(loginUser.getId(), listRParam);
        } catch (Exception e) {
            log.error("listReceiverControlRAndLastUsed Exception:[{}]", e);
        }
        if (listRResult != null) {
            if (!CollectionUtils.isEmpty(listRResult.getResult())) {
                rPairSourceParam.setNoCamera(false)
                        .setRid(listRResult.getResult().get(0).getPeerId())
                        .setPageNum(1);

                if (rPairSourceParam.getPageSize() == 0) {
                    rPairSourceParam.setPageSize(30);
                }

            }
        }


        // 如果搜索列表里面没有这个R, 但是上次操作的话，仍然展示这个R的 source 信息
        PageInfo<Device> rPairSourceResult = userDeviceService.pageReceiverControlSource(loginUser.getId(), rPairSourceParam);


        UserDeviceSearchInitVo listRInitVo = new UserDeviceSearchInitVo();
        listRInitVo.setContent(listRResult)
                .setParam(listRParam);

        UserDeviceSearchInitVo rPairSourceInitVo = new UserDeviceSearchInitVo()
                .setContent(rPairSourceResult)
                .setParam(rPairSourceParam);

        Map<String, Object> result = new HashMap<>();

        result.put("listR", listRInitVo);
        result.put("rPairSource", rPairSourceInitVo);

        return ResultUtil.success(result);

    }

    /**
     * 需要和 webR 保持一致，对 type 进行分类
     *
     * @param loginUser loginUser
     * @return Result
     */
    @GetMapping("/v2/advancedControlWithInit")
    public Result advancedControlWithInitV2(@Logined LoginUser loginUser) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }

        String rid = "";

        // 获取behavior,如果没有就进行初始化
        UserBehavior userBehavior = new UserBehavior()
                .setUserId(loginUser.getId())
                .setPn(UserBehaviorConstant.Pn.ADVANCE_CONTROL)
                .setServerName(UserBehaviorConstant.ServerName.USER)
                .setRemark(UserBehaviorConstant.Remark.LIST_R + "," + UserBehaviorConstant.Remark.R_PAIR_SOURCE_V2);

        Result<Map<String, String>> userBehaviors = userBehaviorService.getUserBehaviors(userBehavior);
        SearchDeviceParam listRParam;
        SearchDeviceParam rPairSourceParam;

        ListRResult listRResult = null;
        if (StringUtils.equals(ResultUtil.SUCCESS, userBehaviors.getErrorCode())) {
            Map<String, String> result = userBehaviors.getResult();

            String listRParamStr = result.get(UserBehaviorConstant.Remark.LIST_R);

            if (StringUtils.isEmpty(listRParamStr)) {
                listRParam = SearchDeviceParam.initForListR();
            } else {
                try {
                    listRParam = JsonUtil.toObject(listRParamStr, SearchDeviceParam.class);
                } catch (IOException e) {
                    listRParam = SearchDeviceParam.initForListR();
                    log.error("parse LIST_R user behavior failed", e);
                }
            }

            listRParam.setToken(false);
            try {
                listRResult = userDeviceService.listReceiverControlRAndLastUsed(loginUser.getId(), listRParam,
                        UserBehaviorConstant.Remark.R_PAIR_SOURCE_V2);
            } catch (Exception e) {
                log.error("listRResult failed", e);
            }
            if (listRResult != null) {
                if (!CollectionUtils.isEmpty(listRResult.getResult())) {
                    rid = listRResult.getResult().get(0).getPeerId();
                }
            }


            String rPairSourceParamStr = result.get(UserBehaviorConstant.Remark.R_PAIR_SOURCE_V2);

            if (StringUtils.isEmpty(rPairSourceParamStr)) {
                rPairSourceParam = SearchDeviceParam.initForRPairSourceV2(rid);
            } else {
                try {
                    rPairSourceParam = JsonUtil.toObject(rPairSourceParamStr, SearchDeviceParam.class);
                } catch (IOException e) {
                    rPairSourceParam = SearchDeviceParam.initForRPairSourceV2(rid);
                    log.error("parse R_PAIR_SOURCE_V2 user behavior failed", e);
                }
            }
        } else {
            listRParam = SearchDeviceParam.initForListR();
            rPairSourceParam = SearchDeviceParam.initForRPairSourceV2(rid);
        }
        if (listRResult!=null){
            if (!CollectionUtils.isEmpty(listRResult.getResult())) {
                rPairSourceParam.setNoCamera(false)
                        .setPageNum(1);

                if (rPairSourceParam.getPageSize() == 0) {
                    rPairSourceParam.setPageSize(30);
                }

            }
        }

        rPairSourceParam.setSyncWebR(Boolean.TRUE);
        Map<String, Object> groupDevices = userDeviceService.groupForAdvanceControl(loginUser.getId(), rPairSourceParam);
        UserDeviceSearchInitVo listRInitVo = new UserDeviceSearchInitVo();
        listRInitVo.setContent(listRResult)
                .setParam(listRParam);


        UserDeviceSearchInitVo rPairSourceInitVoPack = new UserDeviceSearchInitVo()
                .setContent(groupDevices.get("sourcePack"))
                .setParam(rPairSourceParam);

        UserDeviceSearchInitVo rPairSourceInitVoGrid = new UserDeviceSearchInitVo()
                .setContent(groupDevices.get("sourceGrid"));

        UserDeviceSearchInitVo rPairSourceInitVoExt = new UserDeviceSearchInitVo()
                .setContent(groupDevices.get("sourceExt"));
        //查询R端的sourceTypeList
        Long totalGLinkNumber = 0L;
        int totalRTILNumber = 0;
        int totalLocalSDINumber = 0;
        boolean isGLink = rPairSourceParam.isGLink();
        boolean isRTIL = rPairSourceParam.isRTil();
        boolean isLocalSDI = rPairSourceParam.isLocalSdi();
        UserDeviceSearchInitVo rPairGLinkInitVoGrid = new UserDeviceSearchInitVo();
        UserDeviceSearchInitVo rPairRTILInitVoGrid = new UserDeviceSearchInitVo();
        UserDeviceSearchInitVo rPairLocalSDIInitVoGrid = new UserDeviceSearchInitVo();
        String sourceTypeList = userBehaviorService.getRSourceListToRedis(rid);
        if (StringUtils.isEmpty(sourceTypeList)) {

            Result<String> result = null;
            //根据Rid 查询R的sourceTypeList
            try {
                result = userDeviceService.getRSourceTypeList(rid);
                if (result != null) {
                    sourceTypeList = result.getResult();
                    userBehaviorService.setRSourceListToRedis(rid, result.getResult());
                }
            } catch (Exception e) {
                log.error("getRSourceTypeList Exception:[{}]", e);
            }
        }
        if (!StringUtils.isEmpty(sourceTypeList)) {
            //根据sourceTypeList查询对应source
            if (sourceTypeList.contains("GLinkPeerManager") && isGLink) {//包含glink
                PageInfo<ExtendExternal> gLinkList = deviceFeignService.getGLinkList(rPairSourceParam);
                if (gLinkList !=null && !CollectionUtils.isEmpty(gLinkList.getList())) {
                    rPairGLinkInitVoGrid.setContent(gLinkList);
                    totalGLinkNumber = gLinkList.getTotal();

                }
            }
            if (sourceTypeList.contains("AgoraPeerManager") && isRTIL) {//RTIL //需要从R端获取
                try {
                    Result<String> rTILkList = deviceFeignService.getRTILList(rid);
                    if ("0x0".equals(rTILkList.getErrorCode())) {
                        if (rTILkList.getResult().equals("[]")) {
                            rPairRTILInitVoGrid.setContent(null);
                        } else {
                            String result = this.conditionRtil(rPairSourceParam.getCondition(), rTILkList.getResult());
                            rPairRTILInitVoGrid.setContent(result);
                        }

                        if (!StringUtils.isEmpty(rTILkList.getResult())) {
                            JSONArray rTILkListArr = JSON.parseArray(rTILkList.getResult());
                            totalRTILNumber = rTILkListArr.size();
                        }
                    }
                } catch (Exception e) {
                    log.error("rTILkList Exception:[{}]", e);
                }

            }
            if (sourceTypeList.contains(LocalConstant.STRING_LOCAL_SDI_PEER_MANAGER) && isLocalSDI) {//包含localSDI
                try {
                    List<Device> localSDIFromWebR = deviceFeignService.getLocalSDIFromWebR(rPairSourceParam.getRid());
                    PageInfo<Device> pageInfo = new PageInfo<>();
                    pageInfo.setPageNum(rPairSourceParam.getPageNum());
                    pageInfo.setPageSize(rPairSourceParam.getPageSize());
                    if (!CollectionUtils.isEmpty(localSDIFromWebR)) {
                        if (StringUtils.isNotEmpty(rPairSourceParam.getCondition())) {
                            String condition = rPairSourceParam.getCondition();
                            localSDIFromWebR.stream().filter(s -> StringUtils.containsIgnoreCase(s.getPeerId(), condition)
                                    || StringUtils.containsIgnoreCase(s.getName(), condition)).collect(Collectors.toList());
                        }
                        pageInfo.setTotal(localSDIFromWebR.size());
                        pageInfo.setList(localSDIFromWebR);
                        rPairLocalSDIInitVoGrid.setContent(pageInfo);
                        totalLocalSDINumber = localSDIFromWebR.size();
                    }
                } catch (Exception e) {
                    log.error("advancedControlWithInit>>>>>getLocalSDIException,rid:[{}],e:[{}]", rid, e);
                }
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("listR", listRInitVo);
        result.put("sourcePack", rPairSourceInitVoPack);
        result.put("sourceGrid", rPairSourceInitVoGrid);
        result.put("sourceExt", rPairSourceInitVoExt);
        result.put("totalPackNumber", groupDevices.get("totalPackNumber"));
        result.put("totalGridNumber", groupDevices.get("totalGridNumber"));
        result.put("totalExtNumber", groupDevices.get("totalExtNumber"));
        result.put("rFeatureList", sourceTypeList);

        if (isGLink) {
            result.put("sourceGLink", rPairGLinkInitVoGrid);
            result.put("totalGLinkNumber", totalGLinkNumber);
        }
        if (isRTIL) {
            result.put("sourceRTIL", rPairRTILInitVoGrid);
            result.put("totalRTILNumber", totalRTILNumber);
        }
        if (isLocalSDI) {
            result.put("totalLocalSDINumber", totalLocalSDINumber);
            result.put("sourceLocalSDI", rPairLocalSDIInitVoGrid);
        }

        return ResultUtil.success(result);

    }

    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @PostMapping("/pageRExtendExternalSource")
    public Result<Object> pageRExtendExternalSource(@Logined LoginUser loginUser,
                                                    ExtendExternalParam param) {
        Long totalGLinkNumber = 0L;
        int totalRTILNumber = 0;
        int totalLocalSDINumber = 0;
        boolean isGLink = param.isGLink();
        boolean isRTIL = param.isRTil();
        boolean isLocalSDI = param.isLocalSdi();
        String rid = param.getRid();
        UserDeviceSearchInitVo rPairGLinkInitVoGrid = new UserDeviceSearchInitVo();
        UserDeviceSearchInitVo rPairRTILInitVoGrid = new UserDeviceSearchInitVo();
        UserDeviceSearchInitVo rPairLocalSDIInitVoGrid = new UserDeviceSearchInitVo();
        String sourceTypeList = userBehaviorService.getRSourceListToRedis(param.getRid());
        if (StringUtils.isEmpty(sourceTypeList)) {

            Result<String> result = null;
            //根据Rid 查询R的sourceTypeList
            try {
                result = userDeviceService.getRSourceTypeList(rid);
                if (result != null) {
                    sourceTypeList = result.getResult();
                    userBehaviorService.setRSourceListToRedis(rid, result.getResult());
                }
            } catch (Exception e) {
                log.error("getRSourceTypeList Exception:[{}]", e);
            }
        }
        SearchDeviceParam searchDeviceParam = new SearchDeviceParam();
        searchDeviceParam.setRid(rid);
        searchDeviceParam.setGLink(param.isGLink());
        searchDeviceParam.setRTil(param.isRTil());
        searchDeviceParam.setLocalSdi(param.isLocalSdi());
        searchDeviceParam.setPageNum(param.getPageNum());
        searchDeviceParam.setPageSize(param.getPageSize());
        searchDeviceParam.setSyncWebR(param.isSyncWebR());
        searchDeviceParam.setCondition(param.getCondition());
        if (!StringUtils.isEmpty(sourceTypeList)) {
            //根据sourceTypeList查询对应source
            if (sourceTypeList.contains("GLinkPeerManager") && param.isGLink()) {//包含glink
                PageInfo<ExtendExternal> gLinkList = deviceFeignService.getGLinkList(searchDeviceParam);
                if (gLinkList != null && !CollectionUtils.isEmpty(gLinkList.getList())) {
                    rPairGLinkInitVoGrid.setContent(gLinkList);
                    totalGLinkNumber = gLinkList.getTotal();

                }
            }
            if (sourceTypeList.contains("AgoraPeerManager") && param.isRTil()) {//RTIL //需要从R端获取
                try {
                    Result<String> rTILkList = deviceFeignService.getRTILList(param.getRid());
                    if ("0x0".equals(rTILkList.getErrorCode())) {
                        if (rTILkList.getResult().equals("[]")) {
                            rPairRTILInitVoGrid.setContent(null);
                        } else {
                            String result = this.conditionRtil(param.getCondition(), rTILkList.getResult());
                            rPairRTILInitVoGrid.setContent(result);
                        }

                        if (!StringUtils.isEmpty(rTILkList.getResult())) {
                            JSONArray rTILkListArr = JSON.parseArray(rTILkList.getResult());
                            totalRTILNumber = rTILkListArr.size();
                        }
                    }
                } catch (Exception e) {
                    log.error("msg:{},e:{}",e.getMessage(),e);
                }
            }
            if (StringUtils.containsIgnoreCase(sourceTypeList,LocalConstant.STRING_LOCAL_SDI_PEER_MANAGER)
                    && param.isLocalSdi()) {//LocalSDI //需要从R端获取
                try {
                    List<Device> localSDIFromWebR = deviceFeignService.getLocalSDIFromWebR(param.getRid());
                    PageInfo<Device> pageInfo = new PageInfo<>();
                    pageInfo.setPageNum(param.getPageNum());
                    pageInfo.setPageSize(param.getPageSize());
                    if (!CollectionUtils.isEmpty(localSDIFromWebR) && StringUtils.isNotEmpty(param.getCondition())) {
                        localSDIFromWebR= localSDIFromWebR.stream().filter(s -> StringUtils.containsIgnoreCase(s.getPeerId(), param.getCondition())
                                || StringUtils.containsIgnoreCase(s.getName(), param.getCondition())).collect(Collectors.toList());
                    }
                    if (!CollectionUtils.isEmpty(localSDIFromWebR)) {
                        pageInfo.setTotal(localSDIFromWebR.size());
                        pageInfo.setList(localSDIFromWebR);
                        rPairLocalSDIInitVoGrid.setContent(pageInfo);
                        totalLocalSDINumber = localSDIFromWebR.size();
                    }
                } catch (Exception e) {
                    log.error("pageRExtendExternalSource>>>>>>>getLocalSDIException,rid:[{}],e:[{}]", rid, e);
                }
            }
        }
        Map<String, Object> result = new HashMap<>();

        if (isGLink) {
            result.put("sourceGLink", rPairGLinkInitVoGrid);
            result.put("totalGLinkNumber", totalGLinkNumber);
        }
        if (isRTIL) {
            result.put("sourceRTIL", rPairRTILInitVoGrid);
            result.put("totalRTILNumber", totalRTILNumber);
        }
        if (isLocalSDI) {
            result.put("totalLocalSDINumber", totalLocalSDINumber);
            result.put("sourceLocalSDI", rPairLocalSDIInitVoGrid);
        }
        return ResultUtil.success(result);
    }

    /**
     * RTIL模糊查询
     * @param condition
     * @param result
     * @return
     */
    private String conditionRtil(String condition, String result) {
        if (StringUtils.isNotEmpty(condition)) {
            try {
                List<Map> mapList = JsonUtil.toObject(result, List.class);
                mapList = mapList.stream().filter(s -> {
                    if (s.get("IdHex") != null && StringUtils.containsIgnoreCase(s.get("IdHex").toString(), condition)) {
                        return true;
                    }
                    if (s.get("PeerInput") != null) {
                        Map map = (Map) s.get("PeerInput");
                        return !CollectionUtils.isEmpty(map) && map.get("Name") != null
                                && StringUtils.containsIgnoreCase(map.get("Name").toString(), condition);
                    }
                    return false;
                }).collect(Collectors.toList());
                result = JsonUtil.toJsonStr(mapList);
            } catch (IOException e) {
                log.error("conditionRtil>>>>>>>>>>condition rtil exception,result:[{}],e:[{}]", result, e);
            }
        }
        return result;
    }

    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @PostMapping("v2/pageRPairSource")
    public Result<Object> pageRPairSourceV2(@Logined LoginUser loginUser,
                                            @RequestBody SearchDeviceParam param) {
        if (StringUtils.isBlank(param.getRid())) {
            return ResultUtil.paramError();
        }

        PageInfo<Device> list = userDeviceService.pageReceiverControlSource(loginUser.getId(), param);
        return ResultUtil.success(list);
    }


    /**
     * 切换R的时候需要返回三种类型的source列表
     * <p>
     * Source Type 由前端传
     *
     * @param loginUser loginUser
     * @param  param param
     * @return Result
     */
    @PostMapping("/v2/advancedControlRSwitchInit")
    public Result advancedControlRInit(@Logined LoginUser loginUser, @RequestBody SearchDeviceParam param) {


        // init type
        SearchDeviceParam searchDeviceParamPack = SearchDeviceParam.resolverForRPairSourcePack(param);
        PageInfo<Device> sourcePack = userDeviceService.pageReceiverControlSource(loginUser.getId(), searchDeviceParamPack);

        SearchDeviceParam searchDeviceParamGrid = SearchDeviceParam.resolverForRPairSourceGrid(param);
        PageInfo<Device> sourceGrid = userDeviceService.pageReceiverControlSource(loginUser.getId(), searchDeviceParamGrid);

        SearchDeviceParam searchDeviceParamExt = SearchDeviceParam.resolverForRPairSourceExt(param);
        PageInfo<Device> sourceExt = userDeviceService.pageReceiverControlSource(loginUser.getId(), searchDeviceParamExt);

        Map<String, Object> result = new HashMap<>();
        result.put("sourcePack", sourcePack);
        result.put("sourceGrid", sourceGrid);
        result.put("sourceExt", sourceExt);

        return ResultUtil.success(result);

    }

    /**
     *
     * @param loginUser loginUser
     * @param apiType apiType
     * @return Result
     */
    @PostMapping("/homeWithInit")
    public Result homeWithInit(@Logined LoginUser loginUser, @RequestParam String apiType) {

        if (loginUser == null) {
            return ResultUtil.noLogin();
        }

        // 获取behavior,如果没有就进行初始化
        UserBehavior userBehavior = new UserBehavior()
                .setUserId(loginUser.getId())
                .setPn(UserBehaviorConstant.Pn.HOME)
                .setServerName(UserBehaviorConstant.ServerName.USER)
                .setRemark(UserBehaviorConstant.Remark.PAGE_R + "," + UserBehaviorConstant.Remark.USER_SOURCE);

        Result<Map<String, String>> userBehaviors = userBehaviorService.getUserBehaviors(userBehavior);

        SearchDeviceParam listRParam;
        SearchDeviceParam homeSourceParam;


        if (StringUtils.equals(ResultUtil.SUCCESS, userBehaviors.getErrorCode())) {
            Map<String, String> result = userBehaviors.getResult();

            String listRParamStr = result.get(UserBehaviorConstant.Remark.PAGE_R);

            if (StringUtils.isEmpty(listRParamStr)) {
                listRParam = SearchDeviceParam.initForListR();
            } else {
                try {
                    listRParam = JsonUtil.toObject(listRParamStr, SearchDeviceParam.class);
                } catch (IOException e) {
                    listRParam = SearchDeviceParam.initForListR();
                    log.error("parse LIST_R user behavior failed", e);
                }
            }

            String homeUserSource = result.get(UserBehaviorConstant.Remark.USER_SOURCE);

            if (StringUtils.isEmpty(homeUserSource)) {
                homeSourceParam = SearchDeviceParam.initForHomeSource();
            } else {
                try {
                    homeSourceParam = JsonUtil.toObject(homeUserSource, SearchDeviceParam.class);
                } catch (IOException e) {
                    homeSourceParam = SearchDeviceParam.initForHomeSource();
                    log.error("parse R_PAIR_SOURCE user behavior failed", e);
                }
            }
        } else {
            listRParam = SearchDeviceParam.initForListR();
            homeSourceParam = SearchDeviceParam.initForRPairSource();
        }

        // get behavior finish

        PageInfo<Device> listR = null;

        listRParam.setToken(false);
        listRParam.setPageNum(1);
        listRParam.setPageSize(15);

        listR = userDeviceService.pageR(loginUser.getId(), listRParam);

        Object content = new Object();

        if (homeSourceParam.getPageSize() == 0) {
            homeSourceParam.setPageSize(15);
        }

        if (homeSourceParam.getPageNum() == 0) {
            homeSourceParam.setPageNum(1);
        }

        if (StringUtils.equals("SourceContent", apiType)) {
            homeSourceParam.setBattery(false);
            homeSourceParam.setBookmarks(true);
            homeSourceParam.setBookmarkDevice(true);
            content = userDeviceService.pageMySource(loginUser.getId(), homeSourceParam);
        } else if (StringUtils.equals("SourceList", apiType)) {
            homeSourceParam.setBattery(true);
            homeSourceParam.setBookmarks(true);
            content = userDeviceService.pageMySource(loginUser.getId(), homeSourceParam);
        } else if (StringUtils.equals("SourceMap", apiType)) {
            homeSourceParam.setBattery(false);
            homeSourceParam.setBookmarks(true);
            content = userDeviceService.listUserSourcePosition(loginUser.getId(), homeSourceParam.getCondition(), null);
        }

        UserDeviceSearchInitVo listRInitVo = new UserDeviceSearchInitVo();
        listRInitVo.setContent(listR)
                .setParam(listRParam);

        UserDeviceSearchInitVo homeSourceInitVo = new UserDeviceSearchInitVo()
                .setContent(content)
                .setParam(homeSourceParam);

        Map<String, Object> result = new HashMap<>();

        result.put("pageR", listRInitVo);
        result.put("homeSource", homeSourceInitVo);
        return ResultUtil.success(result);

    }

    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @PostMapping("/pageUserSource")
    public Result<Object> pageUserSource(@Logined LoginUser loginUser,
                                         @RequestBody SearchDeviceParam param) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }

        try {
            UserBehavior userBehavior = new UserBehavior();
            userBehavior.setUserId(loginUser.getId())
                    .setServerName(UserBehaviorConstant.ServerName.USER)
                    .setRemark(UserBehaviorConstant.Remark.USER_SOURCE)
                    .setContent(JsonUtil.toJsonStr(param));
            if (StringUtils.equals(param.getPn(), "sc")) {
                userBehavior.setPn(UserBehaviorConstant.Pn.SOURCE_CONTROL);
            } else if (StringUtils.equals(param.getPn(), "bk")) {
                userBehavior.setPn(UserBehaviorConstant.Pn.BOOKING);
            } else {
                userBehavior.setPn(UserBehaviorConstant.Pn.MY_SOURCE);
            }
            userBehaviorService.setUserBehavior(userBehavior);
        } catch (IOException e) {
            log.error("Set user behavior exception", e);
        }
        param.setBookmarkDevice(true);
        PageInfo<Device> list = userDeviceService.pageMySource(loginUser.getId(), param);
        return ResultUtil.success(list);
    }

    /**
     *
     * @param loginUser loginUser
     * @param param  param
     * @return Result
     */
    @PostMapping("/homePageUserSource")
    public Result<Object> homePageUserSource(@Logined LoginUser loginUser,
                                             @RequestBody SearchDeviceParam param) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }

        try {
            UserBehavior userBehavior = new UserBehavior();
            userBehavior.setUserId(loginUser.getId())
                    .setPn(UserBehaviorConstant.Pn.HOME)
                    .setServerName(UserBehaviorConstant.ServerName.USER)
                    .setRemark(UserBehaviorConstant.Remark.USER_SOURCE)
                    .setContent(JsonUtil.toJsonStr(param));
            userBehaviorService.setUserBehavior(userBehavior);
        } catch (IOException e) {
            log.error("Set user behavior exception", e);
        }
        param.setBookmarkDevice(true);
        PageInfo<Device> list = userDeviceService.pageMySource(loginUser.getId(), param);
        return ResultUtil.success(list);
    }

    /**
     *
     * @param loginUser loginUser
     * @param apiType apiType
     * @return Result
     */
    @PostMapping("/getParentSourcesBySonId")
    public Result<Object> getParentSourcesBySonId(@Logined LoginUser loginUser, @RequestParam String apiType) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }


        return null;

    }

    /**
     *
     * @param loginUser loginUser
     * @param apiType apiType
     * @return Result
     */
    @PostMapping("/mySourceWithInit")
    public Result<Object> pageUserSourceWithInit(@Logined LoginUser loginUser, @RequestParam String apiType) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }

        UserDeviceSearchInitVo initVo = null;
        try {
            UserBehavior userBehavior = new UserBehavior().setUserId(loginUser.getId())
                    .setPn(UserBehaviorConstant.Pn.MY_SOURCE)
                    .setServerName(UserBehaviorConstant.ServerName.USER)
                    .setRemark(UserBehaviorConstant.Remark.USER_SOURCE);

            Result<String> result = userBehaviorService.getUserBehavior(userBehavior);

            SearchDeviceParam param;

            if (StringUtils.equals(ResultUtil.SUCCESS, result.getErrorCode())) {
                String paramString = result.getResult();

                if (StringUtils.isEmpty(paramString)) {
                    param = SearchDeviceParam.initForMySource();
                } else {
                    try {
                        param = JsonUtil.toObject(paramString, SearchDeviceParam.class);
                    } catch (IOException e) {
                        param = SearchDeviceParam.initForMySource();
                        log.error("parse user behavior failed", e);
                    }
                }
            } else {
                param = SearchDeviceParam.initForMySource();
            }


            Object content = new Object();

            if (param.getPageSize() == 0) {
                param.setPageSize(15);
            }

            if (param.getPageNum() == 0) {
                param.setPageNum(1);
            }

            if (StringUtils.equals("SourceContent", apiType)) {
                param.setBattery(false);
                param.setBookmarks(false);
                param.setBookmarkDevice(true);
                param.setMySource(1);
                content = userDeviceService.pageMySource(loginUser.getId(), param);
            } else if (StringUtils.equals("SourceList", apiType)) {
                param.setBattery(true);
                param.setBookmarks(true);
                param.setBookmarkDevice(true);
                content = userDeviceService.pageMySource(loginUser.getId(), param);
            } else if (StringUtils.equals("SourceMap", apiType)) {
                param.setBattery(false);
                param.setBookmarks(false);
                content = userDeviceService.listUserSourcePosition(loginUser.getId(), param.getCondition(), null);
            }


            initVo = new UserDeviceSearchInitVo();

            initVo.setContent(content)
                    .setParam(param);
        } catch (Exception e) {
            log.error("===mySourceWithInit exception==", e);
        }

        return ResultUtil.success(initVo);
    }

    /**
     *
     * @param loginUser loginUser
     * @param apiType  apiType
     * @return Result
     */
    @PostMapping("/sourceControlWithInit")
    public Result<Object> sourceControlWithInit(@Logined LoginUser loginUser, @RequestParam String apiType) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }

        UserDeviceSearchInitVo initVo = null;
        try {
            UserBehavior userBehavior = new UserBehavior().setUserId(loginUser.getId())
                    .setPn(UserBehaviorConstant.Pn.SOURCE_CONTROL)
                    .setServerName(UserBehaviorConstant.ServerName.USER)
                    .setRemark(UserBehaviorConstant.Remark.USER_SOURCE);

            Result<String> result = userBehaviorService.getUserBehavior(userBehavior);

            SearchDeviceParam param;

            if (StringUtils.equals(ResultUtil.SUCCESS, result.getErrorCode())) {
                String paramString = result.getResult();

                if (StringUtils.isEmpty(paramString)) {
                    param = SearchDeviceParam.initForMySource();
                } else {
                    try {
                        param = JsonUtil.toObject(paramString, SearchDeviceParam.class);
                    } catch (IOException e) {
                        param = SearchDeviceParam.initForMySource();
                        log.error("parse user behavior failed", e);
                    }
                }
            } else {
                param = SearchDeviceParam.initForMySource();
            }


            Object content = new Object();

            if (param.getPageSize() == 0) {
                param.setPageSize(15);
            }

            if (param.getPageNum() == 0) {
                param.setPageNum(1);
            }

            if (StringUtils.equals("SourceContent", apiType)) {
                param.setBattery(false);
                param.setBookmarks(false);
                content = userDeviceService.pageMySource(loginUser.getId(), param);
            } else if (StringUtils.equals("SourceList", apiType)) {
                param.setBattery(true);
                param.setBookmarks(true);
                content = userDeviceService.pageMySource(loginUser.getId(), param);
            } else if (StringUtils.equals("SourceMap", apiType)) {
                param.setBattery(false);
                param.setBookmarks(false);
                content = userDeviceService.listUserSourcePosition(loginUser.getId(), param.getCondition(), null);
            }


            initVo = new UserDeviceSearchInitVo();

            initVo.setContent(content)
                    .setParam(param);
        } catch (Exception e) {
            log.error("===mySourceWithInit exception==", e);
        }

        return ResultUtil.success(initVo);
    }

    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @GetMapping("/listSourceAvailableR")
    public Result<Object> listSourceAvailableR(@Logined LoginUser loginUser, SearchSourcePairedRParam param) {

        List<Device> list = userDeviceService.listSourceAvailableR(loginUser.getId(), param);

        return ResultUtil.success(list);
    }


    /**
     * 查询source用户下的R和token配对的R
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @GetMapping("/pageSourceAvailableR")
    public Result<Object> pageSourceAvailableR(@Logined LoginUser loginUser, SearchSourcePairedRParam param) {
        PageInfo<Device> list = userDeviceService.pageSourceAvailableR(loginUser.getId(), param);
        return ResultUtil.success(list);
    }


    /**
     * 查询source用户下的R和token配对的R
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     */
    @GetMapping("/pageSourceAvailableRSort")
    public Result<Object> pageSourceAvailableRSort(@Logined LoginUser loginUser, SearchSourcePairedRParam param) {
        PageInfo<Device> list = userDeviceService.pageSourceAvailableRSort(loginUser.getId(), param);
        return ResultUtil.success(list);
    }

    /**
     * 查询用户下的R包含R的状态
     *
     * @param loginUser 当前当前登陆的账户
     * @param param     查询条  件
     * @return Result
     */
    @GetMapping("/pageAllUserRNoStatus")
    public Result<Object> pageAllUserR(@Logined LoginUser loginUser, SearchSourcePairedRParam param) {
        PageInfo<SimpleDeviceVo> list = userDeviceService.pageAllUserRNoStatus(loginUser.getId(), param);
        return ResultUtil.success(list);
    }

    /**
     * 查询用户下R的状态以及是否含有globalGridFeature的Feature
     *
     * @param loginUser 当前当前登陆的账户
     * @param param     查询条件
     * @return Result
     */
    @PostMapping("/pageAllUserRWithGlobalGridFeature")
    public Result<Object> pageAllUserRWithGlobalGridFeature(@Logined LoginUser loginUser, SearchSourcePairedRParam param) {
        PageInfo<FeatureDeviceVo> list = userDeviceService.pageAllUserRWithGlobalGridFeature(loginUser.getId(), param);
        return ResultUtil.success(list);
    }

    /**
     * MySource 页面请求 GridToken 时，下拉 R 列表接口
     *
     * @return Result
     */
    @PostMapping("/pageGridTokenR")
    public Result pageGridTokenR() {
        // TODO
        return ResultUtil.success();
    }


    /**
     * 查询当前登录账户下source 的地理位置
     *
     * @param loginUser 当前登陆的账户
     * @param param     查询条件
     * @return Result
     */
    @PostMapping("listSourcePosition")
    public Result<Object> listSourcePosition(@Logined LoginUser loginUser, @RequestBody SearchDeviceParam param) {


        try {
            UserBehavior userBehavior = new UserBehavior();
            userBehavior.setUserId(loginUser.getId())
                    .setPn(UserBehaviorConstant.Pn.MY_SOURCE)
                    .setServerName(UserBehaviorConstant.ServerName.USER)
                    .setRemark(UserBehaviorConstant.Remark.USER_SOURCE)
                    .setContent(JsonUtil.toJsonStr(param));
            userBehaviorService.setUserBehavior(userBehavior);
        } catch (IOException e) {
            log.error("Set user behavior exception", e);
        }


        List<DevicePositionVo> devicePositionVos = userDeviceService.listUserSourcePosition(loginUser.getId(), param.getCondition(), param.getMapType());

        return ResultUtil.success(devicePositionVos);
    }


    /**
     * 查询当前登录账户下source 的地理位置
     *
     * @param loginUser 当前登陆的账户
     * @param param     查询条件
     * @return Result
     */
    @PostMapping("listSourcePositionForHome")
    public Result<Object> listSourcePositionForHome(@Logined LoginUser loginUser, @RequestBody SearchDeviceParam param) {


        try {
            UserBehavior userBehavior = new UserBehavior();
            userBehavior.setUserId(loginUser.getId())
                    .setPn(UserBehaviorConstant.Pn.HOME)
                    .setServerName(UserBehaviorConstant.ServerName.USER)
                    .setRemark(UserBehaviorConstant.Remark.USER_SOURCE)
                    .setContent(JsonUtil.toJsonStr(param));
            userBehaviorService.setUserBehavior(userBehavior);
        } catch (IOException e) {
            log.error("Set user behavior exception", e);
        }


        List<DevicePositionVo> devicePositionVos = userDeviceService.listUserSourcePosition(loginUser.getId(), param.getCondition(), param.getMapType());

        return ResultUtil.success(devicePositionVos);
    }


    /**
     * 查询当前登录账户下source 的地理位置
     *
     * @param sourceId source id
     * @return Result
     */
    @GetMapping("getSourceLiveRPosition")
    public Result<Object> getReceiverPosition(@RequestParam String sourceId) {

        List<DevicePositionVo> receiverPosition = userDeviceService.getSourceLiveRPosition(sourceId);

        return ResultUtil.success(receiverPosition);
    }

    /**
     * setting页面 查询用户已绑定的设备
     *
     * @param param param
     * @param loginUser loginUser
     * @return Result
     */
    @GetMapping("/listBindedDevice")
    public Result<Object> settingListUserBindDevice(@Logined LoginUser loginUser, @Valid SearchUserDeviceParam param) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        List<SearchUserDeviceVo> list = userDeviceService.listSettingPageUserBindDevice(loginUser.getId(), param);
        return ResultUtil.success(list);
    }

    /**
     * setting页面 查询用户可绑定的设备，父亲包含，但是自己没有的
     *
     * @param param param
     * @return Result
     */
    @GetMapping("/listCanBindDevice")
    public Result<Object> listSettingPageUserCanBindDevice(@Valid SearchUserDeviceParam param) {
        List<SearchUserDeviceVo> list = userDeviceService.listSettingPageUserCanBindDevice(param);
        return ResultUtil.success(list);
    }

    /**
     * setting页面 查询另一个用户的设备，用于分配给某个账号
     *
     * @param userId userId
     * @param email email
     * @return Result
     */
    @GetMapping("/listCanBindDeviceByUserName")
    public Result<Object> listSettingPageUserCanBindDeviceByUserName(@RequestParam String userId, @RequestParam String email) {
        List<SearchUserDeviceVo> list = null;
        try {
            list = userDeviceService.listSettingPageUserCanBindDeviceByUserName(userId, email);
        } catch (ClientException e) {
            return ResultUtil.error("81000701", "User not exist");
        }
        return ResultUtil.success(list);
    }

    /**
     * setting页面 通过SalesForce查询设备，用于分配给某个账号
     *
     * @param userId userId
     * @param account account
     * @return Result
     */
    @GetMapping("/listCanBindDeviceBySalesForce")
    public Result<Object> listCanBindDeviceBySalesForce(@RequestParam String userId, @RequestParam String account) {
        List<SearchUserDeviceVo> list = null;
        try {
            list = userDeviceService.listCanBindDeviceBySalesForce(userId, account);
        } catch (ClientException e) {
            return ResultUtil.error("81000701", "User not exist");
        }
        return ResultUtil.success(list);
    }

    /**
     * Setting页面分配可绑定的设备时，查询某个设备配对的设备
     *
     * @param userId userId
     * @param peerId peerId
     * @return Result
     */
    @GetMapping("/listPairedDevice")
    public Result<Object> listSettingPageUserPairedDevice(@RequestParam String userId, @RequestParam String peerId) {
        List<SearchUserDeviceVo> list = userDeviceService.listSettingPageUserPairedDevice(userId, peerId);
        return ResultUtil.success(list);
    }

    /**
     *
     * @param param param
     * @return Result
     */
    @PostMapping("/existUserBindDevice")
    public Result<Object> existUserBindDevice(@RequestBody PeerIdsParam param) {
        String peerIds = param.getPeerIds();
        if (StringUtils.isBlank(peerIds)) {
            return ResultUtil.success(false);
        }
        boolean exist = userDeviceService.existUserBindDevice(peerIds);
        return ResultUtil.success(exist);
    }

    //    @PostMapping("/correlateUserDevice")
//    public Result<Object> correlateUserDevice(@RequestParam String userId, String addPeerIds, String removePeerIds, String addOwnPeerIds, String removeOwnPeerIds){
//        userDeviceService.correlateUserDevice(userId, addPeerIds, removePeerIds, addOwnPeerIds, removeOwnPeerIds);
//        return ResultUtil.success();
//    }

    /**
     *
     * @param param param
     * @param loginUser loginUser
     * @return 给Anywhere授权owner权限
     */
    @PostMapping("/correlateAnywhere")
    public Result<Object> correlateAnywhere(@RequestBody AnywhereParam param, @Logined LoginUser loginUser) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        userDeviceService.correlateAnywhere(param,loginUser);
        return  ResultUtil.success();
    }
    /**
     *
     * @param data data
     * @param loginUser loginUser
     * @return Result
     */
    @PostMapping("/correlateUserDevice")
    public Result<Object> correlateUserDevice(@RequestBody JSONObject data, @Logined LoginUser loginUser) {
        String userId = null;
        String addPeerIds = null;
        String removePeerIds = null;
        String addOwnPeerIds = null;
        String removeOwnPeerIds = null;
        boolean relateSource = false;
        try {
            userId = data.getString("userId");
            addPeerIds = data.getString("addPeerIds");
            removePeerIds = data.getString("removePeerIds");
            addOwnPeerIds = data.getString("addOwnPeerIds");
            removeOwnPeerIds = data.getString("removeOwnPeerIds");
            relateSource = data.getBoolean("relateSource");
        } catch (Exception e) {
            log.error("correlateUserDevice param error" + e.getMessage());
        }
        userDeviceService.correlateUserDevice(userId, addPeerIds, removePeerIds, addOwnPeerIds, removeOwnPeerIds, loginUser.getId(), relateSource);
        roleUserService.deleteByUserId(userId);
        String operationType = "";
        Map param = new HashMap();
        if (!StringUtils.isEmpty(addPeerIds)) {
            param.put("peerIdList", addPeerIds);
            operationType = UserDeviceRecordConstant.ADDUSERDEVICERELATION;
        }
        if (!StringUtils.isEmpty(removePeerIds)) {
            param.put("peerIdList", removePeerIds);
            operationType = UserDeviceRecordConstant.REMOVEUSERDEVICERELATION;
        }
        if (!StringUtils.isEmpty(addOwnPeerIds)) {
            param.put("peerIdList", addOwnPeerIds);
            operationType = UserDeviceRecordConstant.ADDUSEROWNDEVICE;
        }
        if (!StringUtils.isEmpty(removeOwnPeerIds)) {
            param.put("peerIdList", removeOwnPeerIds);
            operationType = UserDeviceRecordConstant.REMOVEUSEROWNDEVICE;
        }
        //记录操作日志

//        Map peerIdMap = new HashMap();
//        peerIdMap.put("addPeerIds",addPeerIds);
//        peerIdMap.put("removePeerIds",removePeerIds);
//        peerIdMap.put("addOwnPeerIds",addOwnPeerIds);
//        peerIdMap.put("removeOwnPeerIds",removeOwnPeerIds);
        param.put("userIdList", userId);

        userDeviceService.saveUserDeviceRecord(loginUser.getEmail(), loginUser.getId(), operationType, param);
        return ResultUtil.success();
    }

    /**
     * Support 列出和设备有绑定关系的用户
     *
     * @param peerId peerId
     * @return Result
     */
    @GetMapping("/listDeviceBindUser")
    public Result<Object> listDeviceBindUser(@RequestParam String peerId) {
        List<BindDeviceUserVo> list = userDeviceService.listDeviceBindUser(peerId);
        return ResultUtil.success(list);
    }

    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @param pageNum pageNum
     * @param pageSize pageSize
     * @return Result
     */
    @PostMapping("/pageUserExt")
    public Result<Object> pageUserExt(@Logined LoginUser loginUser,
                                      @RequestBody PageExtParam param,
                                      @RequestParam(defaultValue = "1") Integer pageNum,
                                      @RequestParam(defaultValue = "10") Integer pageSize) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        param.setUserId(loginUser.getId());
        PageInfo<ExtVo> list = userDeviceService.pageUserExt(param);
        return ResultUtil.success(list);
    }

    /**
     *
     * @param loginUser loginUser
     * @param peerId peerId
     * @param userIdList userIdList
     * @param relateSource relateSource
     * @return Result
     */
    @PostMapping("/removeDevivecBindUser")
    public Result<Object> removeDevivecBindUser(@Logined LoginUser loginUser,
                                                @RequestParam String peerId,
                                                @RequestParam String userIdList,
                                                @RequestParam(required = false) boolean relateSource
    ) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        if (StringUtils.isEmpty(userIdList) || StringUtils.isEmpty(peerId)) {
            return ResultUtil.paramError();
        }
        try {
            userDeviceService.removeDevivecBindUser(userIdList, peerId, relateSource);
            Map paramMap = new HashMap();
            paramMap.put("peerIdList", peerId);
            paramMap.put("userIdList", userIdList);

            userDeviceService.saveUserDeviceRecord(loginUser.getEmail(), loginUser.getId(), UserDeviceRecordConstant.DEVICEUNBINGUSER, paramMap);
        } catch (Exception e) {
            log.error("msg:{},e:{}",e.getMessage(),e);
            log.error("==removeDevivecBindUser exception==" + e.getMessage());
            return ResultUtil.error("81100701", "remove fail");//
        }

        return ResultUtil.success();
    }

    /**
     *
     * @param loginUser loginUser
     * @param peerId peerId
     * @param relateSource relateSource
     * @return Result
     */
    @PostMapping("/removeAllDevivecBindUser")
    public Result<Object> removeAllDevivecBindUser(@Logined LoginUser loginUser,
                                                   @RequestParam String peerId,
                                                   @RequestParam(required = false) boolean relateSource
    ) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        if (StringUtils.isEmpty(peerId)) {
            return ResultUtil.paramError();
        }
        try {
            List<BindDeviceUserVo> list = userDeviceService.listDeviceBindUser(peerId);
            StringBuffer userIdList = new StringBuffer();
            if (list == null || list.size() == 0) {
                return ResultUtil.error("81100602", "no bind user");//
            }
            for (int i = 0; i < list.size(); i++) {
                if (i == 0) {
                    userIdList.append(list.get(i).getUserId());
                } else {
                    userIdList.append("," + list.get(i).getUserId());
                }

            }
            userDeviceService.removeDevivecBindUser(userIdList.toString(), peerId, relateSource);
            //记录操作日志
            Map paramMap = new HashMap();
            paramMap.put("peerIdList", peerId);
            paramMap.put("userIdList", userIdList);
            userDeviceService.saveUserDeviceRecord(loginUser.getEmail(), loginUser.getId(), UserDeviceRecordConstant.DEVICEUNBINDALLUSER, paramMap);
        } catch (Exception e) {
            log.error("msg:{},e:{}",e.getMessage(),e);
            log.error("==removeAllDevivecBindUser exception==" + e.getMessage());
            return ResultUtil.error("81100601", "remove all fail");//
        }

        return ResultUtil.success();
    }

    /**
     *
     * @param loginUser loginUser
     * @param peerId peerId
     * @param userId userId
     * @param relateSource relateSource
     * @return Result
     */
    @GetMapping("/addDeviceBindUser")
    public Result<Object> addDeviceBindUser(@Logined LoginUser loginUser, @RequestParam String peerId, @RequestParam String userId, @RequestParam(required = false) boolean relateSource) {
        if (StringUtils.isEmpty(peerId) || StringUtils.isEmpty(userId)) {
            return ResultUtil.paramError();
        }
        int success = 0;
        try {
            success = userDeviceService.addDeviceBindUser(userId, peerId, relateSource);
            //记录操作日志
            Map paramMap = new HashMap();
            paramMap.put("peerIdList", peerId);
            paramMap.put("userIdList", userId);
            userDeviceService.saveUserDeviceRecord(loginUser.getEmail(), loginUser.getId(), UserDeviceRecordConstant.DEVICEBINDUSER, paramMap);
        } catch (Exception e) {
            success = 2;
            log.error("==addDeviceBindUser Exception==" + e.getMessage());
            log.error("msg:{},e:{}",e.getMessage(),e);
        }
        if (success == 2) {
            return ResultUtil.error("81100501", "bind user fail");
        } else if (success == 1) {
            return ResultUtil.error("81100502", "this user had binded with this device");
        }
        return ResultUtil.success();
    }

    /**
     * 由于initConfig 页面每次都会调用，所以单独写一个接口供ccswitch调用
     *
     * @param loginUser loginUser
     * @return Result
     */
    @PostMapping(value = "/queryUserBehavior", produces = "application/json; charset=utf-8")
    public Result<Object> queryUserBehavior(@Logined LoginUser loginUser) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        Map behaviorMap = new HashMap();
        String queryRList = "";
        try {
            UserBehavior userBehavior = userBehaviorService.userBehavior(loginUser.getId(), "dn");
            if (userBehavior != null) {
                userBehavior.setUserId(loginUser.getId());
                queryRList = deviceFeignService.queryReceiver(userBehavior, loginUser.getId());
            }
            behaviorMap.put("userBehavior", userBehavior);
            behaviorMap.put("queryListR", queryRList);
        } catch (Exception e) {
            log.error("msg:{},e:{}",e.getMessage(),e);
            log.error("queryUserBehavior exception ===" + e.getMessage());
        }
        return ResultUtil.success(behaviorMap);
    }



    /**
     *   //根据设备id或者名字获取设备列表(未绑定的token device)
     * @param loginUser loginUser
     * @param peerIdOrName  peerIdOrName
     * @param userId userId
     * @return Result
     */
    @GetMapping("/queryTokenDeviceList")
    public Result<Object> queryTokenDeviceList(@Logined LoginUser loginUser, @RequestParam(required = false) String peerIdOrName, @RequestParam String userId) {
        try {
            return userDeviceService.queryTokenDeviceList(loginUser, peerIdOrName, userId);
        } catch (Exception e) {
            log.error("queryTokenDeviceList is error,the error msg{}", e);
            return ResultUtil.error("81100801", "the service is error!");
        }
    }

    /**
     *
     * @param oldPeerId oldPeerId
     * @param newPeerId newPeerId
     * @param gridSource gridSource
     * @param deleteOld deleteOld
     * @return Result
     */

    @PostMapping("/copyDeviceToNewDevice")
    public Result copyDeviceToNewDevice(@RequestParam String oldPeerId, @RequestParam String newPeerId, boolean gridSource, boolean deleteOld) {
        oldPeerId = StringUtils.lowerCase(oldPeerId);
        newPeerId = StringUtils.lowerCase(newPeerId);
        String taskId = MyUtil.getUUID();
        log.error("Start copyDeviceToNewDevice taskId:[{}] oldPeerId:[{}] newPeerId:[{}]", taskId, oldPeerId, newPeerId);
        int result = userDeviceService.copyDeviceToNewDevice(oldPeerId, newPeerId, gridSource, deleteOld, taskId);
        if (result == 1) {
            return ResultUtil.paramError();
        } else if (result == 2) {
            return ResultUtil.error("81001901", "Old device not exist");
        } else if (result == 3) {
            return ResultUtil.error("81001902", "New device not exist");
        } else if (result == 4) {
            return ResultUtil.error("81001903", "Old device is same with new device");
        }
        return ResultUtil.success(result);
    }

    /**
     *
     * @param loginUser loginUser
     * @param sort 排序规则
     * @return Result
     */
    @GetMapping("/queryUserBehaviorForMv")
    public Result<Object> queryUserBehaviorForMv(@Logined LoginUser loginUser,@RequestParam("sort") String sort) {
        Map userBehavior = null;
        try {
            userBehavior = userBehaviorService.queryUserBehaviorList(loginUser.getId(), "mv",sort);
            log.error("===queryUserBehaviorForMv===Result==" + JSON.toJSONString(userBehavior));
        } catch (Exception e) {
            log.error("====queryUserBehaviorForMv Exception==== ==", e);
            return ResultUtil.exception(ResultConstant.UserBehavior.PARSING_BEHAVIOR);
        }
        return ResultUtil.success(userBehavior);
    }

    /**
     * getAllChildBookmarkTreeWithDevice
     * @param  user user
     * @param  bookmarkId 文件夹ID
     * @param  activeNum activeNum
     * @return Result
     */

    @GetMapping("/getAllChildBookmarkTreeWithDevice")
    public Result<Object> getAllChildBookmarkTreeWithDevice(@Logined LoginUser user, @RequestParam("bookmarkId") String bookmarkId, @RequestParam("activeNum") String activeNum) {
        if (user == null) {
            return ResultUtil.noLogin();
        }
        return  userDeviceService.getAllChildBookmarkTreeWithDevice(user,bookmarkId,activeNum);

    }

    /**
     *
     * @param loginUser loginUser
     * @param pn pn
     * @param content cont ent
     * @param remark remark
     * @param type type
     * @return Result
     */
    @RequestMapping("/saveUserBehavior")
    public Result<Object> saveUserBehavior(@Logined LoginUser loginUser, String pn, String content, String remark, String type) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        JSONObject jsonObject = JSONObject.parseObject(content);
        UserBehavior userBehavior = new UserBehavior();
        try {
            if (StringUtils.equals(UserConstant.MultView.MULTVIEW_ADD_RECEIVER, type)) {
                userBehavior.setPn(pn);
                userBehavior.setUserId(loginUser.getId());
                userBehavior.setPeerId(jsonObject.getString("peerId"));
                userBehavior.setRemark(remark);
                userBehavior.setContent(content);
                userBehavior.setUpdateTime(System.currentTimeMillis() + "");
                deviceFeignService.updateUserBehaviorForMv(userBehavior);
            } else if (StringUtils.equals(UserConstant.MultView.MULTVIEW_ADD_CLOUD, type)) {
                // todo
            } else if (StringUtils.equals(UserConstant.MultView.MULTVIEW_REMOVE_RECEIVER, type) || StringUtils.equals(UserConstant.MultView.MULTVIEW_REMOVE_CLOUD, type)) {
                userBehavior.setPn(pn);
                userBehavior.setUserId(loginUser.getId());
                userBehavior.setPeerId(jsonObject.getString("peerId"));
                deviceFeignService.delUserBehavior(userBehavior);
            } else if (StringUtils.equals(UserConstant.MultView.MULTVIEW_SPLIT_SCREEN, type)) {
                userBehavior.setUserId(loginUser.getId());
                userBehavior.setPn(pn);
                userBehavior.setContent(content);
                userBehavior.setRemark(remark);
                userBehavior.setUpdateTime(System.currentTimeMillis() + "");
                deviceFeignService.updateUserBehaviorForMv(userBehavior);
            } else if (StringUtils.equals(UserConstant.MultView.MULTVIEW_SHOW_INFO, type)) {
                userBehavior.setUserId(loginUser.getId());
                userBehavior.setPn(pn);
                userBehavior.setRemark(remark);
                userBehavior.setContent(content);
                userBehavior.setUpdateTime(System.currentTimeMillis() + "");
                deviceFeignService.updateUserBehaviorForMv(userBehavior);
            } else {
                userBehavior.setUserId(loginUser.getId());
                userBehavior.setPn(pn);
                userBehavior.setContent(content);
                userBehavior.setRemark(remark);
                userBehavior.setUpdateTime(System.currentTimeMillis() + "");
                deviceFeignService.updateUserBehaviorForMv(userBehavior);
            }

        } catch (Exception e) {
            log.error("msg:{},e:{}",e.getMessage(),e);
            return ResultUtil.error("0x80100003", "saveUserBehavior fail");
        }
        return ResultUtil.success();
    }


    @Autowired
    private RedisUtil redisUtil;

    /**
     *
     * @return Result
     */
    @GetMapping("/clearCache")
    public Result clearCache() {
        Set<String> keys = redisUtil.keys(UserConstant.RedisKey.CACHE_USER_DEVICE + "*");
        int num = 0;
        if (!CollectionUtils.isEmpty(keys)) {
            num = keys.size();
            for (String key : keys) {
                redisUtil.delete(key);
            }
        }
        return ResultUtil.success(num);
    }

    /**
     * 保存用户偏好设置
     *
     * @param loginUser loginUser
     * @param userPreferenceParam userPreferenceParam
     * @return Result
     */
    @PostMapping("/setPreference")
    public Result setPreference(@Logined LoginUser loginUser, @RequestBody UserPreferenceParam userPreferenceParam) {
        try {
            if (loginUser == null) {
                return ResultUtil.noLogin();
            }
            if (StringUtils.isEmpty(userPreferenceParam.getPn())) {
                return ResultUtil.paramError("PageFunction can not be null or empty");
            }
            if (StringUtils.isEmpty(userPreferenceParam.getContent())) {
                return ResultUtil.paramError("IsPreference can not be null or empty");
            }
            UserBehavior userBehavior = new UserBehavior();
            userBehavior.setUserId(loginUser.getId())
                    .setPn(userPreferenceParam.getPn())
                    .setServerName(UserBehaviorConstant.ServerName.USER)
                    .setRemark(UserBehaviorConstant.Remark.PREFERENCE)
                    .setContent(userPreferenceParam.getContent());
            userBehaviorService.setUserBehavior(userBehavior);
        } catch (Exception e) {
            return ResultUtil.exception();
        }
        return ResultUtil.success();
    }

    /**
     * 保存用户偏好设置
     *
     * @param loginUser loginUser
     * @param userPreferenceParam userPreferenceParam
     * @return Result
     */
    @PostMapping("/listPreference")
    public Result listPreference(@Logined LoginUser loginUser, @RequestBody UserPreferenceParam userPreferenceParam) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        UserBehavior userBehavior = new UserBehavior();
        userBehavior.setUserId(loginUser.getId());
        userBehavior.setRemark(UserBehaviorConstant.Remark.PREFERENCE);
        if (!StringUtils.isEmpty(userPreferenceParam.getPn())) {
            userBehavior.setPn(userPreferenceParam.getPn());
        }
        if (!StringUtils.isEmpty(userPreferenceParam.getContent())) {
            userBehavior.setContent(userPreferenceParam.getContent());
        }
        List<UserBehavior> behaviorList = userBehaviorService.userBehaviorList(userBehavior);
        return ResultUtil.success(behaviorList);
    }

    /**
     *
     * @param loginUser loginUser
     * @param pageInfoBookMarkParam pageInfoBookMarkParam
     * @return Result
     * @throws Exception 编译异常
     */
    //分页查询bookmark
    @PostMapping("/pageInfoBookMark")
    public Result<PageInfo<PageInfoBookMarkParam>> pageInfoBookMark(@Logined LoginUser loginUser, @RequestBody PageInfoBookMarkParam pageInfoBookMarkParam) throws Exception {

        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        String userId = loginUser.getId();
        return userDeviceService.pageInfoBookMark(userId, pageInfoBookMarkParam);
    }

    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     * @throws Exception 编译异常
     */
    //在bookmark下分页查询R
    @PostMapping("/pageInfoRByBookMark")
    public Result<PageInfo<Device>> pageInfoRByBookMark(@Logined LoginUser loginUser, @RequestBody PageInfoRByBookMarkParam param) throws Exception {

        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        String bookmarkId = param.getBookmarkId();
        List<String> status = param.getStatus();
        String search = param.getSearch();
        Integer pageSize = param.getPageSize();
        Integer pageNum = param.getPageNum();
        String userId = loginUser.getId();
        return userDeviceService.pageInfoRByBookMark(userId, bookmarkId, status, search, pageSize, pageNum);

    }

    /**
     *
     * @param loginUser loginUser
     * @param bookmarkId bookmarkId
     * @return Result
     * @throws Exception 编译异常
     */
    //stopAll按钮 关闭该bookmark下(不包括子文件夹下)所有的直播,改变live状态
    @PostMapping("/stopAllByBookMarkId")
    public Result stopAllByBookMarkId(@Logined LoginUser loginUser, @RequestParam("bookmarkId") String bookmarkId) throws Exception {

        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
         return  userDeviceService.stopAllByBookMarkId(bookmarkId);


    }

    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     * @throws Exception 编译异常
     */
    @PostMapping("/startAllByBookMarkId")
    public Result startAllByBookMarkId(@Logined LoginUser loginUser, @RequestBody PageInfoRByBookMarkParam param) throws Exception {

        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        return userDeviceService.startAllByBookMarkId(param);

    }


    /**
     *
     * @param loginUser loginUser
     * @param param param
     * @return Result
     * @throws Exception 编译异常
     */
    @PostMapping("/selectLivingR")
    public Result selectLivingR(@Logined LoginUser loginUser, @RequestBody PageInfoRByBookMarkParam param) throws Exception {

        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        String bookmarkId = param.getBookmarkId();
        List<Device> listLivingR = new ArrayList<>();

        List<String> list = userDeviceService.selectRByBookmarkId(bookmarkId);
        if (list.size()!=0) {
            for (String s : list) {
                Device device = deviceFeignService.getCurrentDevice(s);
                if (device != null) {
                    if ("2".equals(device.getStatus())) {
                        listLivingR.add(device);
                    }
                }
            }
        }
        return ResultUtil.success(listLivingR);
    }

    /**
     * 查询该用户下有TimeLock的feature的receiver集合
     * @param loginUser 用户信息
     * @param param 查询条件
     * @return 满足的集合
     */
    @PostMapping("listReceiverByTimeLockFeature")
    public Result listReceiverByTimeLockFeature(@Logined LoginUser loginUser, @RequestBody SearchDeviceParam param) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        return ResultUtil.success(userDeviceService.listReceiverByTimeLockFeature(loginUser.getId(), param));
    }

    /**
     * 查询该用户下指定R配对的有TimeLock的feature的Pack集合
     * @param loginUser 用户信息
     * @param param 查询条件
     * @return 满足的集合
     */
    @PostMapping("listPackByTimeLockFeature")
    public Result listPackByTimeLockFeature(@Logined LoginUser loginUser, @RequestBody TimeLockPackParam param) {
        if (loginUser == null) {
            return ResultUtil.noLogin();
        }
        return ResultUtil.success(userDeviceService.listPackByTimeLockFeature(loginUser.getId(), param));
    }
}
